package JZ29_最小的K个数;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.PriorityQueue;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> list = new ArrayList<>();
        if (input == null || input.length == 0 || input.length < k || k ==0){
            return list;
        }
        PriorityQueue<Integer> maxQueue = new PriorityQueue<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        for (int i = 0; i < k; i++){
            maxQueue.offer(input[i]);
        }

        for (int i = k; i < input.length; i++){
            if (maxQueue.peek() > input[i]){
                maxQueue.poll();
                maxQueue.offer(input[i]);
            }
        }

        for (int i = 0; i < k; i++){
            list.add(maxQueue.poll());
        }
        return list;

    }

}